<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <el-row class="cat_select">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            v-model="selectedCateIds"
            :options="allCateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader
        ></el-col>
      </el-row>

      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="buttonActive" @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="tabData" stripe border>
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, item)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="operate">
                <el-button type="primary" @click="showEditDialog(operate.row)"
                  >编辑</el-button
                >
                <el-button type="danger" @click="deleteAttr(operate.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="buttonActive" @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="tabData" stripe border>
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, item)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="operate">
                <el-button type="primary" @click="showEditDialog(operate.row)"
                  >编辑</el-button
                >
                <el-button type="danger" @click="deleteAttr(operate.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="activeTabName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="closeAddAttrDialog"
    >
      <el-form
        :model="addAttrForm"
        :rules="AttrRules"
        ref="addAttrFormRef"
        label-width="80px"
      >
        <el-form-item
          :label="activeTabName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="activeTabName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="closeEditAttrDialog"
    >
      <el-form
        :model="editAttrForm"
        :rules="AttrRules"
        ref="editAttrFormRef"
        label-width="80px"
      >
        <el-form-item
          :label="activeTabName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      allCateList: [],
      selectedCateIds: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeTabName: 'many',
      tabData: [],
      addDialogVisible: false,
      addAttrForm: {
        attr_name: ''
      },
      AttrRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editAttrForm: {}
    }
  },
  computed: {
    buttonActive() {
      if (this.selectedCateIds.length === 3) {
        return false
      } else {
        return true
      }
    },
    cateId() {
      if (this.selectedCateIds.length === 3) {
        return this.selectedCateIds[2]
      }
      return null
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.allCateList = res.data
    },
    async handleChange() {
      if (this.selectedCateIds.length !== 3) {
        this.selectedCateIds = []
        this.tabData = []
        return
      }
      this.getParams()
    },
    handleTabClick() {
      this.getParams()
    },
    async getParams() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeTabName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputTagValue = ''
      })
      this.tabData = res.data
    },
    closeAddAttrDialog() {
      this.$refs.addAttrFormRef.resetFields()
    },
    addAttr() {
      this.$refs.addAttrFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.activeTabName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParams()
      })
    },
    showEditDialog(row) {
      this.getAttrById(row)
      this.editDialogVisible = true
    },
    closeEditAttrDialog() {
      this.$refs.editAttrFormRef.resetFields()
    },
    async getAttrById(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          params: {
            attr_sel: this.activeTabName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editAttrForm = res.data
    },
    editDialog() {
      this.$refs.editAttrFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editAttrForm.attr_id}`,
          {
            attr_name: this.editAttrForm.attr_name,
            attr_sel: this.activeTabName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getParams()
      })
    },
    async deleteAttr(row) {
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParams()
    },
    showInput(row) {
      row.inputVisible = true
      // 页面被重新渲染之后再执行回调
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row) {
      const inputTagValue = row.inputTagValue
      if (inputTagValue.trim().length !== 0) {
        row.attr_vals.push(inputTagValue)
      }
      row.inputVisible = false
      row.inputTagValue = ''
      this.saveAttrvals(row)
    },
    async saveAttrvals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    handleClose(row, item) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
      this.saveAttrvals(row)
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
.cat_select {
  margin-top: 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-top: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
  margin-top: 10px;
}
</style>
